package cassys.actions.manageUser;

import cassys.application.DTOs.UserDTO;
import cassys.domain.user.User;
import com.opensymphony.xwork2.ActionSupport;


import cassys.ejb.clients.UserManagementDelegate;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Validateable;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.interceptor.ServletRequestAware;

/**
 * <code>Set welcome message.</code>
 */
public class UserAction extends ActionSupport
        implements Validateable, ServletRequestAware, ModelDriven<UserDTO> {

    private final static String DISPLAY_USER = "displayUser";
    private final static String USERINFO = "userInfo";
    private UserDTO userDTO = new UserDTO();
    private List<String> roleList;
    // private static final String ADMIN = "admin";
    private HttpServletRequest request;

    public List<String> getRoleList() {
        roleList = new ArrayList(3);
        roleList.add("ADMIN");
        roleList.add("LECTURER");
        roleList.add("STUDENT");
        return roleList;
    }
    private UserManagementDelegate userDelegate;

    public UserAction() {
        userDelegate = new UserManagementDelegate();
    }

    public String goToHome() throws Exception {
        return SUCCESS;
    }

    @Override
    public String execute() throws Exception {
        System.out.println("---------execute-----------");
        return DISPLAY_USER;
    }

    private User populateUser(UserDTO userDTO, User user) {

        System.out.println("editUser");
        user.setUserId(userDTO.getUserId());
        user.setFirstName(userDTO.getFirstName());
        user.setLastName(userDTO.getLastName());
        user.setPassword(userDTO.getPassword());
        user.setStreetName(userDTO.getStreetName());
        user.setCity(userDTO.getCity());
        user.setContactNumber(userDTO.getContactNumber());
        user.setEmail(userDTO.getEmail());
        user.setPincode(userDTO.getPincode());
        user.setUserSeqNo(userDTO.getUserSeqNo());
        user.setDelInd(userDTO.getDelInd());
        return user;

    }

    public String displayUser() throws Exception {

        System.out.println("displayUser");
        String userId = userDTO.getUserId();
        /* if((userId==null)||(userId.equals(""))) {
        return "input";
        }*/

        List<User> userList = userDelegate.getUser(userId);

        if (userList != null && userList.size() > 0 && userList.get(0) != null) {
            userDTO.setUserId(userList.get(0).getUserId());
            userDTO.setFirstName(userList.get(0).getFirstName());
            userDTO.setLastName(userList.get(0).getLastName());
            userDTO.setPassword(userList.get(0).getPassword());
            userDTO.setStreetName(userList.get(0).getStreetName());
            userDTO.setCity(userList.get(0).getCity());
            userDTO.setContactNumber(userList.get(0).getContactNumber());
            userDTO.setEmail(userList.get(0).getEmail());
            userDTO.setPincode(userList.get(0).getPincode());
            userDTO.setUserSeqNo(userList.get(0).getUserSeqNo());

            return DISPLAY_USER;
        } else {
            return USERINFO;
        }
    }

    public String modifyUser() throws Exception {

        System.out.println("userDTO.getUserSeqNo()  " + userDTO.getUserSeqNo());
        userDTO.setDelInd(0);
        User user = populateUser(userDTO, new User());
        String firstName = userDTO.getFirstName().trim();
        String lastName = userDTO.getLastName().trim();
        String userId = userDTO.getUserId().trim();
        String password = userDTO.getPassword().trim();

        if (!firstName.equals("") || !lastName.equals("") || !userId.equals("")
                || !password.equals("") || checkNumberValidation()) {
            userDelegate.modifyUser(user, userDTO.getRole());
            return USERINFO;
        } else {
            return ERROR;
        }
    }

    private boolean checkNumberValidation() throws Exception {
        String contactNumber = userDTO.getContactNumber().trim();
        String pincode = userDTO.getPincode().trim();
        if (!contactNumber.equals("") && !pincode.equals("")) {
            for (int i = 0; i < contactNumber.length(); i++) {
                if (!Character.isDigit(contactNumber.charAt(i))) {
                    return false;
                }
            }

            for (int i = 0; i < pincode.length(); i++) {
                if (!Character.isDigit(pincode.charAt(i))) {
                    return false;
                }
            }
        } else {
            return false;
        }
        return true;
    }

    public String uploadStudentCSV() throws Exception {
        return SUCCESS;
    }

    public void setServletRequest(HttpServletRequest request) {
        this.request = request;
    }

    public String uploadCSV() throws Exception {
        System.out.println("uploadCSV");

        try {
            //create BufferedReader to read csv file
            String uploadfileName = (String) request.getSession().getServletContext().getRealPath("");
            System.out.println("CSV uploadfileName " + uploadfileName);
            BufferedReader br = new BufferedReader(new FileReader(uploadfileName));
            System.out.println("CSV uploadfileName " + uploadfileName);
            String strLine = "";
            String str = "";
            StringTokenizer st = null;
            List csvContent = new ArrayList();
            int lineNumber = 0, tokenNumber = 0;
            List fileRecords = new ArrayList();

            while ((strLine = br.readLine()) != null) {
                lineNumber++;
                str = strLine;
                fileRecords.add(str);
            }
            //read comma separated file line by line
            for (int i = 0; i < fileRecords.size(); i++) {
                String record = (String) fileRecords.get(i);

                System.out.println("CSV File " + record);
                try {
                    st = new StringTokenizer(record, ",");
                    while (st.hasMoreTokens()) {
                        csvContent.add(st.nextToken().trim());
                    }
                } catch (NoSuchElementException e) {
                }
            }
        } catch (Exception e) {
        }
        return ERROR;
    }

    public String deleteUser() throws Exception {
        System.out.println("editUser");
        System.out.println("userDTO.getUserSeqNo()  " + userDTO.getUserSeqNo());
        userDTO.setDelInd(1);
        User user = populateUser(userDTO, new User());
        userDelegate.modifyUser(user, "");
        return SUCCESS;
    }

    public String saveUser() throws Exception {
        String firstName = userDTO.getFirstName();
        String lastName = userDTO.getLastName();
        String userId = userDTO.getUserId();
        String password = userDTO.getPassword();
        System.out.println("getName---;----ServletActionContext-----------" + userId);
        System.out.println("userId---;----ServletActionContext-----------" + password);
        if ((firstName == null) || (firstName.equals("")) || (lastName == null) || (lastName.equals(""))
                || (userId == null) || (userId.equals("")) || (password == null) || (password.equals(""))) {
            return "input";
        }
        try {
            userDelegate.saveUser(this.userDTO);
        } catch (Exception e) {
            return ERROR;
        }
        return SUCCESS;
    }

    @Override
    public UserDTO getModel() {
        // throw new UnsupportedOperationException("Not supported yet.");
        return this.userDTO;
    }
}
